package com.ouc.dataMange.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ouc.common.config.OUCAjaxResult;
import com.ouc.common.utils.DateUtils;
import com.ouc.common.utils.file.FileUtils;
import com.ouc.dataMange.service.ISysDataSetService;
import com.ouc.dataMange.service.ISysMemoryDeviceService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ouc.common.annotation.Log;
import com.ouc.common.core.controller.BaseController;
import com.ouc.common.core.domain.AjaxResult;
import com.ouc.common.enums.BusinessType;
import com.ouc.dataMange.domain.SysUploadFile;
import com.ouc.dataMange.service.ISysUploadFileService;
import com.ouc.common.utils.poi.ExcelUtil;
import com.ouc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * uploadFileController
 *
 * @author ouc
 * @date 2025-07-16
 */
@RestController
@RequestMapping("/dataMange/uploadFile")
public class SysUploadFileController extends BaseController {
  @Autowired
  private ISysUploadFileService sysUploadFileService;

  @Autowired
  private ISysMemoryDeviceService memoryDeviceService;

  @Autowired
  private ISysDataSetService dataSetService;

  /**
   * 查询uploadFile列表
   */
  @PreAuthorize("@ss.hasPermi('dataMange:uploadFile:list')")
  @GetMapping("/list")
  public TableDataInfo list(SysUploadFile sysUploadFile) {
    startPage();
    List<SysUploadFile> list = sysUploadFileService.selectSysUploadFileList(sysUploadFile);
    return getDataTable(list);
  }

  /**
   * 导出uploadFile列表
   */
  @PreAuthorize("@ss.hasPermi('dataMange:uploadFile:export')")
  @Log(title = "uploadFile", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  public void export(HttpServletResponse response, SysUploadFile sysUploadFile) {
    List<SysUploadFile> list = sysUploadFileService.selectSysUploadFileList(sysUploadFile);
    ExcelUtil<SysUploadFile> util = new ExcelUtil<SysUploadFile>(SysUploadFile.class);
    util.exportExcel(response, list, "uploadFile数据");
  }

  /**
   * 获取uploadFile详细信息
   */
  @PreAuthorize("@ss.hasPermi('dataMange:uploadFile:query')")
  @GetMapping(value = "/{fileId}")
  public AjaxResult getInfo(@PathVariable("fileId") Integer fileId) {
    return success(sysUploadFileService.selectSysUploadFileByFileId(fileId));
  }

  /**
   * 新增uploadFile
   */
  @PreAuthorize("@ss.hasPermi('dataMange:uploadFile:add')")
  @Log(title = "uploadFile", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody SysUploadFile sysUploadFile) {
    return toAjax(sysUploadFileService.insertSysUploadFile(sysUploadFile));
  }

  /**
   * 修改uploadFile
   */
  @PreAuthorize("@ss.hasPermi('dataMange:uploadFile:edit')")
  @Log(title = "uploadFile", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@RequestBody SysUploadFile sysUploadFile) {
    return toAjax(sysUploadFileService.updateSysUploadFile(sysUploadFile));
  }

  /**
   * 删除uploadFile
   */
  @PreAuthorize("@ss.hasPermi('dataMange:uploadFile:remove')")
  @Log(title = "uploadFile", businessType = BusinessType.DELETE)
  @DeleteMapping("/{fileIds}")
  public AjaxResult remove(@PathVariable Integer[] fileIds) {
    return toAjax(sysUploadFileService.deleteSysUploadFileByFileIds(fileIds));
  }

  @ResponseBody
  @RequestMapping("/uploadFile")
  public OUCAjaxResult uploadFile(MultipartFile[] file,
                                  @RequestParam(value = "userId") Integer userId,
                                  @RequestParam(value = "userName") String userName,
                                  @RequestParam(value = "dataMemoryId") Integer dataMemoryId,
                                  @RequestParam(value = "dataSetId") Integer dataSetId,
                                  @RequestParam(value = "dataMangeId1") Integer dataMangeId1,
                                  @RequestParam(value = "dataMangeId2") Integer dataMangeId2) throws IOException {
    try {
      SysUploadFile sysUploadFile = new SysUploadFile();
      sysUploadFile.setUserId(userId);
      sysUploadFile.setUserName(userName);
      sysUploadFile.setDataMemoryId(dataMemoryId);
      sysUploadFile.setDataSetId(dataSetId);
      sysUploadFile.setDatamangeId1(dataMangeId1);
      sysUploadFile.setDatamangeId2(dataMangeId2);
      sysUploadFile.setUploadTime(DateUtils.getNowDate());
      sysUploadFile.setViewTime(DateUtils.getNowDate());
      sysUploadFile.setUploadNum(0);
      sysUploadFile.setViewNum(0);

      for (MultipartFile multipartFile : file) {
        String[] fileSplit = multipartFile.getOriginalFilename().split("/");
        String fileDir = memoryDeviceService.selectSysMemoryDeviceById(sysUploadFile.getDataMemoryId()).getSysMemoryDevice()
            + dataSetService.selectSysDataSetById(sysUploadFile.getDataSetId()).getDataSetDevice() + "\\" + sysUploadFile.getUserId();
        File newFile = new File(fileDir);
        if (!newFile.exists()) {
          newFile.mkdirs();
        }
        String fileName = fileSplit[fileSplit.length - 1];
        multipartFile.transferTo(new File(fileDir, fileName));
        sysUploadFile.setFilePath("\\" + sysUploadFile.getUserId() + "\\" + fileName);
        sysUploadFile.setFileInfo(multipartFile.getSize() / (1024 * 1024) + 1);

        sysUploadFileService.insertSysUploadFile(sysUploadFile);
      }
      return OUCAjaxResult.ok("文件成功上传");
    } catch (Exception e) {
      return OUCAjaxResult.error("未成功上传");
    }
  }

  /**
   * 根据数据集，查询数据统计列表
   */
  @ResponseBody
  @GetMapping("/selectDataSet")
  public OUCAjaxResult selectDataSet(SysUploadFile sysUploadFile) {
    return OUCAjaxResult.ok(sysUploadFileService.selectDataSet(sysUploadFile));
  }

  /**
   * 查询最近查看列表（5个）
   */
  @ResponseBody
  @RequestMapping("/selectSysUploadFileListByViewTime")
  public OUCAjaxResult selectSysUploadFileListByViewTime(SysUploadFile sysUploadFile) {
    return OUCAjaxResult.ok(sysUploadFileService.selectSysUploadFileListByViewTime(sysUploadFile));
  }

  /**
   * 更新文件查看时间
   *
   * @param fileId 文件id
   * @return
   */
  @ResponseBody
  @RequestMapping("/updateViewTime")
  public OUCAjaxResult updateViewTime(@RequestParam(value = "fileId") Integer fileId) {
    SysUploadFile sysUploadFile = new SysUploadFile();
    sysUploadFile.setFileId(fileId);
    sysUploadFile.setViewTime(DateUtils.getNowDate());
    sysUploadFileService.updateSysUploadFile(sysUploadFile);
    return OUCAjaxResult.ok("已更新");
  }

  /**
   * 查询最新上传列表（5个）
   */
  @ResponseBody
  @RequestMapping("/selectSysUploadFileListByUpload")
  public OUCAjaxResult selectSysUploadFileListByUpload(SysUploadFile sysUploadFile) {
    return OUCAjaxResult.ok(sysUploadFileService.selectSysUploadFileListByUpload(sysUploadFile));
  }

  @ResponseBody
  @RequestMapping("/getFileTreeList")
  public OUCAjaxResult getFileTreeList(String fileName) {
    try {
      return OUCAjaxResult.ok(FileUtils.getFileTreeList(fileName));
    }catch (Exception e){
      return OUCAjaxResult.error("此文件路径有误");
    }

  }
}
